package conson.tech.manage.common.service;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * ClassName: RestTemplateClient
 * Description:
 * Author: HXL
 * Date: 2020/5/8 10:19 上午
 * Version: 1.0
 */
@Slf4j
@Service("restTemplateClient")
public  class RestTemplateClient {
    @Autowired
    RestTemplate restTemplate;
    public Object getForEntity(String url){
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK)return null;
        String body = responseEntity.getBody();
        return  JSONUtil.toBean(body, Object.class);
    }
    public String postForEntityJSON(String url,String jsonParam) {
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            log.info("-----------RestTemplateClient->postForEntityJSON 发送接口的 url:{} param:{} headers:{}",url,jsonParam,headers);
            HttpEntity<String> formEntity = new HttpEntity<>(jsonParam, headers);
            Long startTime = System.currentTimeMillis();
            //解决返回值中文乱码问题
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, formEntity, String.class);
            log.info("-----------RestTemplateClient->postForEntityJSON 发送接口返回结果:{} ",responseEntity);
            log.info("-----------RestTemplateClient->postForEntity 发送接口耗时:{}毫秒",System.currentTimeMillis()-startTime);
            if (responseEntity != null && responseEntity.getStatusCode()== HttpStatus.OK){
                return responseEntity.getBody();
            }else {
                log.info("-----------RestTemplateClient->postForEntityJSON 调用接口失败");
                throw new RuntimeException("接口调用失败");
            }
        } catch (RuntimeException e) {
            log.info("-----------RestTemplateClient->postForEntityJSON 调用接口出现异常:",e);
            throw new RuntimeException("服务异常");
        }
    }
    public String postForEntity(String url,Map param) {
        return postForEntity(url,param, null);
    }
    public String postForEntity(String url, Map<String,Object> param,HttpHeaders headers) {
        return postForEntity(url, param, headers, null);
    }
    public String postForEntity(String url, Map<String,Object> param, HttpHeaders headers, MediaType mediaType) {
        log.info("-----------RestTemplateClient->postForEntity 发送接口的 url:{} param:{} headers:{}",url,param,headers);
        try {
            if (headers == null) {
                headers = new HttpHeaders();
            }
            mediaType = mediaType==null?MediaType.MULTIPART_FORM_DATA:mediaType;
            headers.setContentType(mediaType);
            MultiValueMap multiValueMap = new LinkedMultiValueMap();
            for (Map.Entry<String,Object> entry : param.entrySet()){
                multiValueMap.add(entry.getKey(), entry.getValue());
            }
            HttpEntity formEntity = new HttpEntity<>(multiValueMap, headers);
            Long startTime = System.currentTimeMillis();
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, formEntity,String.class);
            log.info("-----------RestTemplateClient->postForEntity 发送接口返回结果:{} ",responseEntity);
            log.info("-----------RestTemplateClient->postForEntity 发送接口耗时:{}毫秒",System.currentTimeMillis()-startTime);
            if (responseEntity.getStatusCode()== HttpStatus.OK){
                return responseEntity.getBody();
            }else {
            log.info("-----------RestTemplateClient->postForEntity 调用接口失败");
                throw new RuntimeException("接口调用失败");
            }
        }catch (Exception e){
        log.info("-----------RestTemplateClient->postForEntity 调用接口出现异常:",e);
            throw new RuntimeException("服务异常");
        }
    }
}
